package modbus.com.controller;

import modbus.com.serialport.SerialPortManager;
import modbus.com.serialport.SerialPortSend;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.math.BigInteger;
import java.util.List;

/**
 *
 */
@Controller
@RequestMapping("/serialPort")
public class SerialPortController {
    /**
     * 查看本地所有串口
     *
     * @return
     */
    @GetMapping("/list")
    @ResponseBody
    public List<String> listPorts() {
        List<String> portList = SerialPortManager.getSerialPortList();
        if (!portList.isEmpty()) {
            return portList;
        }
        return null;
    }

    /**
     * 前端测试向串口传输数据
     *
     * @param hexData
     * @return
     * @throws InterruptedException
     */
    @PostMapping("/send/{hexData}")
    @ResponseBody
    public String sendPorts(@PathVariable("hexData") String hexData) throws InterruptedException {
        System.out.println(hexData);

        SerialPortSend.send("COM2", "报文", 9600, 8, 1, 0);
        return "fail";
    }

    /**
     * 模拟串口返回的报文解析数据
     *
     * @param hexData
     * @return
     * @throws InterruptedException
     */
    @PostMapping("/dispose/{hexData}")
    @ResponseBody
    public String dispose(@PathVariable("hexData") String hexData) throws InterruptedException {
        //去掉报文头
        String toTop = hexData.substring(6, hexData.length());
        //去掉尾部校验
        String toTrail = toTop.substring(0, toTop.length() - 4);
        //数据位16进制转10进制结果
        Integer count = decodeHEX(toTrail);
        //在数字后两位前插入小数点
        StringBuilder stringBuilder = new StringBuilder(count.toString());
        //添加小数点
        stringBuilder.insert(count.toString().length() - 2, ".");
        //封装json数据传输
        System.out.println(decodeHEX(hexData.substring(0, 2)) + "号设备采集数据----->>" + stringBuilder);
        //  WebSoceketLightBoard.sendTextMessage(jsonObject.toJSONString());
        return stringBuilder.toString();
    }

    //将16进制的数转换为10进制 输入的是16进制
    public static int decodeHEX(String hexs) {
        //hexs 表示是16进制的数
        BigInteger bigInteger = new BigInteger(hexs, 16);
        int value = bigInteger.intValue();
        return value;
    }

}
